import axios from 'axios';
import {Message} from 'element-ui';
import {getToken, setToken} from '@/utils/token';

const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API,
    method: 'POST',
    timeout: 8000
});

/**
 * 弹出错误提示
 */
function alertErrorMsg(msg) {
    Message({
        message: msg,
        type: 'error',
        duration: 2000
    });
    throw new Error(msg);
}

// 统一请求拦截
service.interceptors.request.use(
    req => {
        const token = getToken();
        if (token) {
            const prefix = 'Bearer ';
            const authorization = token.startsWith(prefix) ? token : prefix + token;
            req.headers['Authorization'] = authorization;
        }
        return req;
    },
    error => {
        alertErrorMsg(error.message);
    }
);

// 统一响应拦截
service.interceptors.response.use(
    resp => {
        const {token, code, msg, error, err} = resp.data;
        if (code && code !== 200) {
            alertErrorMsg(msg || error || err);
        }
        if (token) {
            setToken(token);
        }
        return resp.data;
    },
    error => {
        console.log('error: ', error);
        alertErrorMsg('系统异常, 请联系管理员');
    }
);

export default service;
